import React, { Component } from 'react';
import { Tabs, Button, Table, Divider, Modal, Form, Icon, Select, Drawer, Tree } from 'antd';
import '@/assets/css/settings';
import * as APIService from '../../axios/api';
import * as utils from '../../utils/action';
import { openModalMessage } from '../../components/TableCustomize';
import AddForm from './AddForm';
const { TabPane } = Tabs;
const { Option } = Select;
const { confirm } = Modal;
const { TreeNode } = Tree;

var keys = [];
class App extends Component {
	state = {
		loading: false, dataSource: [], visible: false,
		modalData: '',//选中的数据
		handleType: 0,//新增0 修改1
		topId: 0,
		options: [],
		drawer: false,
		treeData: [],
		checkedKeys: '',
		expandedKeys: [],
		key: 1,
		authData: [],
		items: [],
		typeValue: '',
		returnRole: []
	};
	componentDidMount() {
		this.fetch();
		this.getMenusList(this.state.key)
		this.returnRole()
	}
	returnRole = () => {
		APIService.returnRole().then((value) => {
			if (value.data.code !== 200) {
				openModalMessage(value.data.msg)
				return
			}
			this.setState({
				returnRole: value.data.data
			})
		})
	}
	getMenusList = (key) => {
		APIService.getMenus(key).then(data => {
			const dataSource = data.data.data;
			this.setState({
				treeData: dataSource
			})
		})
	}
	//初始化加载数据
	fetch = () => {
		this.setState({ loading: true })
		APIService.getRoles().then(data => {
			const dataSource = data.data.data.data;
			this.setState({
				dataSource: dataSource,
				loading: false,
			})
		})


	}
	getRoleMenuList = (id, type) => {
		APIService.queryRoleMenuList(id, type).then(dataSource => {
			this.setState({
				authData: dataSource.data.data
			}, () => this.defalutKeys(this.state.authData));
		})
	}
	handleChangeTab = key => {
		if (parseInt(key) === 1) {
			this.setState({ key })
			this.getMenusList(key);
			this.getRoleMenuList(this.state.modalData.roleId, key);

		} else if (parseInt(key) === 2) {
			this.setState({ key })
			this.getMenusList(key)
			this.getRoleMenuList(this.state.modalData.roleId, key);
		}
		else if (parseInt(key) === 3) {
			this.setState({ key })
			this.getMenusList(key)
			this.getRoleMenuList(this.state.modalData.roleId, key);
		}
	};

	//添加修改角色提交
	submitMenu = (e) => {
		this.props.form.validateFields((err, values) => {
			if (!err) {

				if (this.state.handleType === 0) {
					values = Object.assign({}, values, { creatorId: parseInt(localStorage.getItem('userId')) })
				} else {
					values = Object.assign({}, values, { updaterId: parseInt(localStorage.getItem('userId')), id: this.state.modalData.roleId })
				}
				const that = this;
				// console.log(values);
				APIService.addOrUpdateRole(values).then(data => {
					if (data.data.code !== 200) {
						utils.openNotification('warning', data.data.msg)
						return
					}
					utils.openNotification('success', '操作成功')
					const { setFieldsValue } = this.props.form
					setFieldsValue({ description: '' })
					that.handleCancel();
					that.props.form.resetFields();
					this.returnRole()
					that.fetch();
				})

			} else {
				console.log(err);
			}
		});
	}
	// 确认添加
	submitMenuRoleCode = () => {
		this.formDrawer.validateFields((err, value) => {
			if (err) return;
			console.log(value);
			APIService.addOrUpdateRole(value).then(data => {
				if (data.data.code !== 200) {
					openModalMessage('warning', data.data.msg)
					return
				}
				this.setState({
					roleCode: false
				}, () => { this.returnRole(); this.fetch() })
			})
		})
	}
	// 取消
	handleCancelRoleCode = () => {
		this.formDrawer && this.formDrawer.resetFields();
		this.setState({
			roleCode: false
		})
	}
	//权限配置提交
	submitSettings = (e) => {
		const that = this;
		const values = { buttonIdList: this.state.checkedKeys.btnkeys, menuIdList: this.state.checkedKeys.menukeys, creatorId: parseInt(localStorage.getItem('userId')), roleId: this.state.modalData.roleId, type: parseInt(this.state.key) }
		APIService.authorityDeploy(values).then(data => {
			if (data.data.code === 200) {
				utils.openNotification('success', '操作成功')
			} else {
				utils.openNotification('warning', data.data.msg)
			}
			that.handleCancel();
			this.returnRole()
			that.fetch();
		})
	}


	//弹出删除框
	showDeleteConfirm = (data) => {
		const that = this;
		confirm({
			title: '确认删除' + '[' + data.roleName + ']？',
			okText: '确认',
			okType: 'danger',
			cancelText: '取消',
			onOk() {
				APIService.deleteRole(data.roleId).then(data => {
					utils.openNotification('success', '删除成功');
					that.fetch();
				}).catch(function (error) {
					utils.openNotification('error', error.message);
				});



			},
			onCancel() {
				console.log('Cancel');
			},
		});
	}

	//0新增  1修改
	showModal = (data, type) => {
		this.returnRole()
		if (type === 1) {
			this.props.form.setFieldsValue({
				name: data.roleName,
				code: data.roleCode,
				description: data.description
			})
		}
		this.setState({
			visible: true,
			modalData: data,
			handleType: type,
		});

	};

	showDrawer = (data) => {
		keys = [];
		this.getRoleMenuList(data.roleId, this.state.key);
		this.setState({
			drawer: true,
			modalData: data,
		});
	};
	defalutKeys = (data) => {

		data.map(item => {

			if (item.children === undefined) {

				keys.push(`btnId:${item.id}`)
			} else if (item.children.length > 0) {

				return (
					this.defalutKeys(item.children)
				);
			} else if (item.children.length === 0 && item.sysMenuButtonList.length > 0) {

				return (
					this.defalutKeys(item.sysMenuButtonList)
				);
			} else if (item.children.length === 0 && item.sysMenuButtonList.length === 0) {
				keys.push(`menuId:${item.id}`)
			}

		});
		// console.log(keys);
		this.setState({
			expandedKeys: keys
		})
	}

	handleCancel = e => {
		const { setFieldsValue } = this.props.form
		this.props.form.resetFields();
		this.setState({
			visible: false,
			drawer: false,
		});
		setFieldsValue({ description: '' })
	};
	//节点加载完毕时触发
	//   onLoadData = treeNode =>
	//   new Promise(resolve => {
	// 	  if (treeNode.props.children) {
	// 		  resolve();
	// 		  return;
	// 	  }
	// 	  setTimeout(() => {
	// 		treeNode.props.dataRef.children = [
	// 		  { title: 'Child Node', key: `${treeNode.props.eventKey}-0` },
	// 		  { title: 'Child Node', key: `${treeNode.props.eventKey}-1` },
	// 		];
	// 		this.setState({
	// 		  treeData: [...this.state.treeData],
	// 		});
	// 		resolve();
	// 	  }, 1000);
	//   });
	//生成树
	renderTreeNodes = data =>
		data.map(item => {
			if (item.children === undefined) {
				return <TreeNode title={item.buttonName} key={`btnId:${item.id}`} {...item} dataRef={item} selectable />;
			}
			if (item.children.length > 0) {

				return (
					<TreeNode title={item.name} key={`menuId:${item.id}`} dataRef={item} selectable>
						{this.renderTreeNodes(item.children)}
					</TreeNode>
				);
			} else if (item.children.length === 0 && item.sysMenuButtonList.length > 0) {
				return (
					<TreeNode title={item.name} key={`menuId:${item.id}`} dataRef={item} selectable>
						{this.renderTreeNodes(item.sysMenuButtonList)}
					</TreeNode>
				);
			} else {
				return <TreeNode title={item.name} key={`menuId:${item.id}`} {...item} dataRef={item} selectable />;
			}

		});
	//权限框选中事件
	onCheck = (checkedKeys, e) => {
		var menukeys = [];
		var btnkeys = [];
		for (var key of checkedKeys) {
			if (key.indexOf('menuId')) {
				btnkeys.push(parseInt(key.substring(key.indexOf(':') + 1)));
			} else {
				menukeys.push(parseInt(key.substring(key.indexOf(':') + 1)));
			}
		}
		//halfCheckedKeys 有关联的父级值
		for (var key2 of e.halfCheckedKeys) {
			menukeys.push(parseInt(key2.substring(key2.indexOf(':') + 1)));
		}
		this.setState({ checkedKeys: { btnkeys: btnkeys, menukeys: menukeys }, expandedKeys: checkedKeys });
	};

	onChange = (e) => {
		const { setFieldsValue } = this.props.form
		const { returnRole } = this.state
		let name = {}
		returnRole.forEach((value, index) => {
			name[value.code] = [value]
		})
		this.setState({
			name: name[e]
		})
		setFieldsValue({ name: undefined })
	}
	addItem = () => {
		this.setState({
			roleCode: true
		})
	};
	render() {
		const columns = [
			{
				title: '序号',
				width: '10%',
				render: (text, record, index) => `${index + 1}`,
			},

			{
				title: '角色编码',
				dataIndex: 'roleCode',
			},
			{
				title: '角色名称',
				dataIndex: 'roleName',
			},
			{
				title: '描述',
				dataIndex: 'description',
			},
			{
				title: '操作',
				width: '12%',
				render: (text, record) => {
					return <span>
						<a onClick={() => this.showModal(record, 1)}>修改</a>
						<Divider type="vertical" />

						<a onClick={() => this.showDrawer(record)}>权限配置</a>
						<Divider type="vertical" />
						<a onClick={() => this.showDeleteConfirm(record)}>
							删除
						</a>
					</span>
				}
			}
		];
		const { getFieldDecorator } = this.props.form;
		const formItemLayout_addMenu = {
			labelCol: {
				sm: { span: 8 }
			},
			wrapperCol: {
				sm: { span: 9 }
			}
		};
		var operations = <div className="mydiv" > <Button icon="plus" onClick={() => this.showModal([], 0)} type="primary" > 新增 </Button></div >
		return (
			<div className="shadow-radius">
				<Tabs tabBarExtraContent={operations} defaultActiveKey="1" onChange={this.handleChangeTab}>
					<TabPane tab="角色管理" key="1">
						<Table columns={columns} rowKey={(record) => record.roleId} scroll={{ y: 500 }} dataSource={this.state.dataSource} pagination={false} loading={this.state.loading} />
					</TabPane>

				</Tabs>

				<Modal
					width='600px'
					title="新增/修改"
					visible={this.state.visible}
					centered
					onOk={this.submitMenu}
					onCancel={this.handleCancel}
					okText="保存"
					cancelText="取消"
				>
					<Form {...formItemLayout_addMenu}>
						<Form.Item label="角色编码">
							{getFieldDecorator('code', {
								rules: [{ required: true, message: '请填写角色编码！' }]
							})(
								<Select
									onChange={this.onChange}
									dropdownRender={menu => (
										<>
											{menu}
											<Divider style={{ margin: '4px 0' }} />
											<div
												onMouseDown={e => e.preventDefault()}  //阻止关闭（会影响input使用）
												// onClick={e => e.stopPropagation()}
												style={{ display: 'flex', position: 'relative', padding: '0 8px 4px' }}
											>
												{/* <Input
													placeholder="请输入"
													// ref={(ref) => { this.InputRef = ref }}
													value={typeValue}
													// onClick={(e) => { e.preventDefault(); this.InputRef.focus() }}
													onChange={this.onNameChange} style={{ whiteSpace: 'nowrap' }}
													allowClear
												/> */}
												<Button onClick={this.addItem} shape="circle" type="link">
													<Icon type="plus" />添加
												</Button>
											</div>
										</>
									)}
								>
									{
										this.state.returnRole.map((item, index) => {
											return <Option key={item.id} value={item.code}>{item.code}</Option>
										})
									}
								</Select>
							)}
						</Form.Item>
						<Form.Item label="角色名称">
							{getFieldDecorator('name', {
								rules: [{ required: true, message: '请填写角色名称！' }]
							})(<Select
								dropdownRender={menu => (
									<>
										{menu}
										<Divider style={{ margin: '4px 0' }} />
										<div
											onMouseDown={e => e.preventDefault()}  //阻止关闭（会影响input使用）
											style={{ display: 'flex', position: 'relative', padding: '0 8px 4px' }}
										>
											<Button onClick={this.addItem} shape="circle" type="link">
												<Icon type="plus" />添加
											</Button>
										</div>
									</>
								)}
							>
								{
									this.state.name ? this.state.name.map((item, index) => {
										return <Option key={item.id} value={item.name}>{item.name}</Option>
									}) : null
								}
							</Select>)}
						</Form.Item>
						<Form.Item label="描述">
							{getFieldDecorator('description')(<textarea style={{ width: '100%', height: '4rem' }} />)}
						</Form.Item>

					</Form>

				</Modal >


				<Drawer title="权限配置" placement="right" closable={true} onClose={this.handleCancel} visible={this.state.drawer}
					width='600px' >

					<Tabs defaultActiveKey="1" onChange={this.handleChangeTab}>
						<TabPane tab="管理端" key="1">
							<Tree multiple checkedKeys={this.state.expandedKeys} checkable onCheck={this.onCheck}>
								{this.renderTreeNodes(this.state.treeData)}
							</Tree>
						</TabPane>
						<TabPane tab="移动端" key="2">
							<Tree multiple checkedKeys={this.state.expandedKeys} checkable onCheck={this.onCheck}>
								{this.renderTreeNodes(this.state.treeData)}
							</Tree>
						</TabPane>
						<TabPane tab="平板端" key="3">
							<Tree multiple checkedKeys={this.state.expandedKeys} checkable onCheck={this.onCheck}>
								{this.renderTreeNodes(this.state.treeData)}
							</Tree>
						</TabPane>
					</Tabs>
					<div
						style={{
							position: 'absolute',
							right: 0,
							bottom: 0,
							width: '100%',
							borderTop: '1px solid #e9e9e9',
							padding: '10px 16px',
							background: '#fff',
							textAlign: 'right',
						}}
					>
						<Button onClick={this.handleCancel} style={{ marginRight: 8 }}>
							取消
						</Button>
						<Button type='primary' onClick={this.submitSettings} style={{ marginRight: 8 }}>
							保存
						</Button>
					</div>
				</Drawer >

				<Modal
					title='添加角色编码'
					visible={this.state.roleCode}
					onOk={this.submitMenuRoleCode}
					onCancel={this.handleCancelRoleCode}
					okText="添加"
					cancelText="取消"
				>
					<AddForm
						ref={node => (this.formDrawer = node)}
					/>
				</Modal>
			</div >
		);
	}
}
export default Form.create()(App);